const app = getApp();
import {
    _headerPost,
    _headerGet,
    _get,
    _post
} from '../../../utils/httpUtils.js'
const RSA = require("../../../utils/wx_rsa.js");
Page({
    data: {
        navbarData: {
            showCapsule: 1, //是否显示左上角图标
            title: '上线大酬宾' //导航栏 中间的标题
        },
        height: app.globalData.height,
        share: app.globalData.share,
        html: "",
        showComment: true,
        buyNumber: 1, //默认商品数量
        maskSty: "none",
        showTop: true,
        commentWidth: 330,
        share_uid: '0', //收益人的id ,默认为 0
        userList: [
            "执手听风吟",
            "青芜堤上柳",
            "****醉卧伊人膝",
            "****旧青画",
            "阿斯顿",
            "***芳华",
            "凉夏",
            "**素月姣姣",
            "夏木悠悠",
            "***夏风不燥",
            "梦幻之露",
            "三月枔",
            "**克拉的悲傷",
            "指舞花",
            "匀散一缕过往",
            "*谁暖了 冬季",
            "风月不等闲",
            "**浅安时光",
            "***惆怅已成曲调",
            "浣歌",
            "**恰似旧人归"
        ]
    },

    onLoad(option) {
        let result = [];
        let data = this.data.userList;
        let chunk = 3; //每3个分一组
        for (let i = 0, j = data.length; i < j; i += chunk) {
            result.push(data.slice(i, i + chunk));
        }
        this.setData({
            result: result,
            id: option.id
        })
        // 获取推荐人的id
        if (option.uid) {
            wx.setStorage({
                key: 'uid',
                data: option.uid,
            })
            this.setData({
                share_uid: option.uid
            })
        }

        this.getDetail(option.id)
        // this.getBuyGoodList()
    },

    getDetail(id) {
        let _data = {
            id: id
        }
        _headerGet('/api/Article/detail', _data, res => {
            if (res.data.code == 1) {
                this.setData({
                    nodes: res.data.data,
                    html: res.data.data.article_a_content.replace(/\<img/g, `<img style="width:99%; margin:10px auto; height:auto; display:block"`)
                })
                // 如果是商品,处理商品逻辑
                if (res.data.data.article_a_is_goods != '0') {
                    // console.log(res.data.data.article_a_is_goods)
                    this.setData({
                        purchase: true
                    })
                    this.getGoodsAttr(res.data.data.article_a_id);
                }
                wx.stopPullDownRefresh()
            } else {
                wx.showModal({
                    title: '提示',
                    content: res.data.msg,
                    showCancel: false
                })
                wx.stopPullDownRefresh()
                return
            }
        })
    },
    getGoodsAttr(article_id) { //获取商品属性
        _post('/api/goods/get_goods_detail', {
            article_id: article_id
        }, res => {
            if (res.data.code == 1) {
                this.setData({
                    goods: res.data.data
                })
                let detail = res.data.data.goodsDetail;
                if (detail.g_spec_format != '') {
                    let child = JSON.parse(detail.g_spec_format)
                    let defChioce = ''
                    //设置属性的状态，并默认选中第一个
                    for (let i = 0; i < child.length; i++) {
                        for (let j = 0; j < child[i].spec_value.length; j++) {
                            if (j == 0) {
                                child[i].spec_value[j].active = true
                                defChioce = defChioce + child[i].spec_id + ':' + child[i].spec_value[j].spec_value_id + ';';
                            } else {
                                child[i].spec_value[j].active = false
                            }
                        }
                    }
                    this.defaultType(defChioce) //设置默认选项
                    this.setData({
                        g_spec_format: child,
                    })
                }
            } else {
                wx.showToast({
                    title: res.data.msg,
                    duration: 2000,
                    icon: 'none'
                })
            }
        })
    },
    // getBuyGoodList() {
    //     _get('/api/goods/buy_goods_list', {
    //         goods_id: '835',
    //         c_client: 'weixinSmall'
    //     }, res => {
    //         console.log(res.data)
    //     })
    // },
    defaultType(choice) { //根据结果判断判断商品类型
        let skuArr = this.data.goods.goodsSku
        for (let k = 0; k < skuArr.length; k++) {
            if (skuArr[k].attr_value_items == choice.substring(0, choice.length - 1)) {
                this.setData({
                    goodsType: skuArr[k]
                })
            }
        }
    },
    labelItemTap(e) {
        // 取消该分类下的子栏目所有的选中状态
        let childs = this.data.g_spec_format[e.currentTarget.dataset.propertyindex].spec_value;
        for (let i = 0; i < childs.length; i++) {
            this.data.g_spec_format[e.currentTarget.dataset.propertyindex].spec_value[i].active = false;
        }
        // 设置当前选中状态
        this.data.g_spec_format[e.currentTarget.dataset.propertyindex].spec_value[e.currentTarget.dataset.propertychildindex].active = true;
        //获取所有的选中规格尺寸数据
        let needSelectNum = this.data.g_spec_format.length;
        let curSelectNum = 0;
        let propertyChildIds = "";
        let propertyChildNames = "";
        //得到选中结果
        for (let i = 0; i < this.data.g_spec_format.length; i++) {
            let childs = this.data.g_spec_format[i].spec_value;
            for (let j = 0; j < childs.length; j++) {
                if (childs[j].active) {
                    curSelectNum++;
                    propertyChildIds = propertyChildIds + this.data.g_spec_format[i].spec_id + ":" + childs[j].spec_value_id + ";"
                    propertyChildNames = propertyChildNames + childs[j].spec_name + ":" + childs[j].spec_value_name + ";"
                }
            }
        }
        //根据结果判断判断商品类型
        let skuArr = this.data.goods.goodsSku
        for (let k = 0; k < skuArr.length; k++) {
            if (skuArr[k].attr_value_items == propertyChildIds.substring(0, propertyChildIds.length - 1)) {
                this.setData({
                    goodsType: skuArr[k]
                })
            }
        }
        this.setData({
            g_spec_format: this.data.g_spec_format
        })
    },
    //数量减少
    numJianTap: function() {
        if (this.data.buyNumber > 1) {
            let currentNum = this.data.buyNumber;
            currentNum--;
            this.setData({
                buyNumber: currentNum
            })
        }
    },
    //数量增加
    numJiaTap: function() {
        if (this.data.buyNumber < this.data.goods.goodsDetail.goods_stock) {
            let currentNum = this.data.buyNumber;
            currentNum++
            this.setData({
                buyNumber: currentNum
            })
        }
    },

    buyNow() { // 立即购买
        if (this.data.goodsType.stock == 0) {
            wx.showToast({
                title: '库存不足哦',
                icon: 'none'
            })
            return
        }
        // 如果用户没有注册绑定推荐人,从缓存里面取uid
        try {
            const share_uid = wx.getStorageSync('uid')
            if (share_uid) {
                this.setData({
                    share_uid: share_uid
                })
            }
        } catch (e) {
            console.log(e)
        }

        let _data = {
            c_client: 'weixinSmall',
            type: 'buyNow',
            skuId: this.data.goodsType.sku_id,
            num: this.data.buyNumber,
            share_uid: this.data.share_uid //受益人id
        }
        wx.navigateTo({
            url: '/pages/public/confirm-order/index?data=' + JSON.stringify(_data)
        })
    },

    handOver(event) { // 获取属性
        let currentId = event.currentTarget.dataset.id;
        this.setData({
            cate_id: currentId,
        })
    },
    closePopupTap() {
        this.setData({
            maskSty: 'none'
        })
    },

    showPopupTap() {
        this.setData({
            maskSty: 'block'
        })
    },
    userlike(e) { // 一级用户评论点赞
        let dataset = e.currentTarget.dataset;
        let _data = {
            'type': 3,
            'id': dataset.id
        }
        let _isZan = this.data.nodes.commentList[dataset.index].is_zan;
        if (_isZan == 1) {
            this.data.nodes.commentList[dataset.index].is_zan = 0;
            this.data.nodes.commentList[dataset.index].zan_count--;
        } else {
            this.data.nodes.commentList[dataset.index].is_zan = 1;
            this.data.nodes.commentList[dataset.index].zan_count++;
        }
        _headerPost('/api/zan/zan', _data, res => {
            if (res.data.code == 1) {
                this.setData({ // 点赞重载数据
                    nodes: this.data.nodes
                })
                wx.showToast({
                    title: res.data.msg,
                    icon: 'success',
                    duration: 2000
                })
            } else if (res.data.code != '-2') {
                wx.showToast({
                    title: res.data.msg,
                    icon: 'none',
                    duration: 2000
                })

            }
        })
    },
    tread(e) { // 评论踩
        let dataset = e.currentTarget.dataset;
        let _isTread = this.data.nodes.commentList[dataset.index].is_tread;
        if (_isTread == 1) {
            this.data.nodes.commentList[dataset.index].is_tread = 0;
        } else {
            this.data.nodes.commentList[dataset.index].is_tread = 1;
        }
        let _data = {
            'c_client': RSA.hex2b64(RSA.KEYUTIL.getKey(app.globalData.publicKey).encrypt(`weixinSmall`)),
            'id': RSA.hex2b64(RSA.KEYUTIL.getKey(app.globalData.publicKey).encrypt(`${e.currentTarget.dataset.id}`))
        }
        _headerPost('/api/article/article_comment_tread', _data, res => {
            if (res.data.code == 1) {
                this.setData({ // 重载数据
                    nodes: this.data.nodes
                })
                wx.showToast({
                    title: res.data.msg,
                    duration: 2000
                })
            }
        })
    },

    onShow: function() {
        // 获取分享人的id
        try {
            const token = wx.getStorageSync('token')
            if (token) {
                this.setData({
                    useruid: token.uid
                })
            }
        } catch (e) {
            console.log(e)
        }
    },
    showBuyBtn() {
        console.log(`触发评论`)
        this.commentFocus()
    },

    commentFocus(e) { //键盘聚焦
        this.setData({
            showComment: false,
            commentWidth: 530,
            buyBtn: true
        })
    },

    commentBlur(e) { //键盘失去焦点
        this.setData({
            showComment: true,
            commentWidth: 330,
            buyBtn: ''
        })
    },
    comment(e) { //评论提交
        let _data = {
            'ac_type': 2,
            'id': this.data.id,
            'content': e.detail.value.content
        }
        console.log(_data)
        _headerPost('/api/comment/addComment', _data, res => {
            // console.log(res.data)
            if (res.data.code == 1) {
                this.getDetail(this.data.id)
                wx.showToast({
                    title: res.data.msg,
                    icon: 'success',
                    duration: 1000
                })
                this.setData({
                    tmpStorage: '' //置空评论框
                })
            } else {
                wx.showToast({
                    title: res.data.msg,
                    duration: 2000,
                    icon: 'none'
                })
            }
        })
    },

    _navback() {
        let pages = getCurrentPages(); // 获取页面堆栈
        pages.length > 1 ? wx.navigateBack() : wx.switchTab({
            url: '/pages/tabBar/specialty/specialty'
        })
    },
    close() {
        //设置空方法来取消冒泡事件
    },

    // 触发转发时间
    onShareAppMessage() {
        let that = this;
        return {
            title: that.data.nodes.article_a_title,
            path: `/pages/activity/line001/detail?id=${that.data.nodes.article_a_id}&uid=${that.data.useruid}`,
            imageUrl: that.data.nodes.article_a_main_pic
        }
    }
})